package com.imu.wys.controller;


import com.imu.wys.model.User;
import com.imu.wys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @RequestMapping(value = {"login"})
    public ModelAndView login(HttpServletRequest request, String username, String password) {
        ModelAndView ma=new ModelAndView();
        User user=userService.findByUserName(username);
        System.out.println(username);
        if(null!=user) {
            if(user.getPassword().equals(password)) {
                request.getSession().setAttribute("existUser", user);
                ma.addObject("user", user);
                ma.setViewName("main");
            }else {
                ma.setViewName("login");
                ma.getModel().put("msg", "密码错误!");
            }
        }else {
            ma.setViewName("login");
            ma.getModel().put("msg", "用户名不存在!");
        }
        return ma;
    }



    @RequestMapping(value = {"register"})
    public ModelAndView register(HttpServletRequest request, String username, String password) {
        ModelAndView ma=new ModelAndView();
        User user = userService.findByUserName(username);
        if(user==null){
            User registerUser = new User();
            registerUser.setUsername(username);
            registerUser.setPassword(password);
            try {
                userService.insertUser(registerUser);
                ma.setViewName("login");
                ma.addObject("user", registerUser);
                ma.getModel().put("msg", "注册成功前往登录！");
            }catch (Exception e){
//                System.out.println(e.getMessage());
                ma.setViewName("register");
                ma.getModel().put("msg", "注册失败！");
            }

        }else { //用户名存在
            ma.setViewName("register");
            ma.getModel().put("msg", "用户名已存在!");
        }
        return ma;
    }

}
